import java.util.*;


public class Solution2 {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();
        if(root == null) {
            return ret;
        }
        boolean flag = false;
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);

        while(!q.isEmpty()) {
            int sz = q.size();
            List<Integer> tmp = new ArrayList<>();
            for(int i = 0; i < sz; i++) {
                TreeNode t = q.poll();
                tmp.add(t.val);
                if(t.left != null) {
                    q.add(t.left);
                }
                if(t.right != null) {
                    q.add(t.right);
                }
            }
            if(flag == true) {
                tmp = reverse(tmp);
            }
            ret.add(tmp);
            flag = !flag;
        }
        return ret;
    }

    public List<Integer> reverse(List<Integer> tmp) {
        List<Integer> ret = new ArrayList<>();
        for(int i = tmp.size() - 1; i >= 0; i--) {
            ret.add(tmp.get(i));
        }
        return ret;
    }

    public List<List<Integer>> zigzagLevelOrder1(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();
        if(root == null) {
            return ret;
        }
        boolean flag = false;
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);

        while(!q.isEmpty()) {
            int sz = q.size();
            List<Integer> tmp = new ArrayList<>();
            for(int i = 0; i < sz; i++) {
                TreeNode t = q.poll();
                tmp.add(t.val);
                if(t.left != null) {
                    q.add(t.left);
                }
                if(t.right != null) {
                    q.add(t.right);
                }
            }
            if(flag == true) {
                Collections.reverse(tmp);
            }
            ret.add(tmp);
            flag = !flag;
        }
        return ret;
    }
}
